<template>
  <div ref="editor" class="textEditor"></div>
</template>
<script lang="ts">
import { upload } from '@/services/course'
import Vue from 'vue'
import E from 'wangeditor'
export default Vue.extend({
  name: 'Wangeditor',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  mounted () {
    this.initEditor()
  },
  methods: {
    initEditor () {
      let curHtml = ''
      const editor = new E(this.$refs.editor as Element)
      editor.config.onchange = (newHtml: string) => {
        curHtml = newHtml
        this.$emit('input', curHtml)
      }
      editor.config.customUploadImg = async (resultFiles: Blob[], insertImgFn: (imgUrl: string) => void) => {
        if (resultFiles.length > 1) {
          this.$message.warning('一次只能上传一张图片')
        }
        try {
          const { data } = await upload(resultFiles[0])
          if (data.code === '000000') {
            insertImgFn(data.data.name)
          } else {
            this.$message.error(`上传图片失败,code:${data.code}`)
          }
        } catch (error) {
          this.$message.error(`上传图片失败,error:${error.message}`)
        }
      }
      editor.create()

      this.$watch('value', function setHtml (newHtml: string) {
        if (newHtml !== curHtml) {
          curHtml = newHtml
          editor.txt.html(newHtml)
        }
      }, { immediate: true })
    }
  }
})
</script>
